package com.yiwei.zxp.activity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.CommissoinCheckApplyBean;
import com.yiwei.zxp.api.bean.ShareGoldExplainBean;
import com.yiwei.zxp.api.model.BankCardListModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.BankTypeEvent;
import com.yiwei.zxp.event.SelectBankEvent;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class WithdrawActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_change_bankcard)
    LinearLayout btnChangeBankcard;
    @BindView(R.id.view_has_bankcard)
    View viewHasBankcard;
    @BindView(R.id.layout_has_bankcard)
    LinearLayout layoutHasBankcard;
    @BindView(R.id.txt_rate)
    TextView txtRate;
    @BindView(R.id.txt_money_true)
    TextView txtMoneyTrue;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.img_bank_icon)
    ImageView imgBankIcon;
    @BindView(R.id.txt_bank_info)
    TextView txtBankInfo;
    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.txt_money_tips)
    TextView txtMoneyTips;
    private Unbinder unbiner;
    private int x30;
    private float rate;
    private String bank_id;
    private boolean is_has_bankcard = false;
    private boolean is_request = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet_withdraw);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        txtTitle.setText("提现");
        txtMoneyTips.setText("余额：" + UserInfoGlobal.getCommission() + "元");
        x30 = getResources().getDimensionPixelSize(R.dimen.x30);
        editMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(UI.toString(editMoney))) {
                    return;
                }

                if (TextUtils.isEmpty(bank_id)) {
                    btnSubmit.setBackgroundResource(R.drawable.btn_uncheck_gredient);
                } else {
                    btnSubmit.setBackgroundResource(R.drawable.btn_check_gredient);
                }
                if (UI.toFloat(editMoney) > Float.valueOf(UserInfoGlobal.getCommission())) {
                    editMoney.setText(Math.floor(Float.valueOf(UserInfoGlobal.getCommission())) + "");
                    return;
                }
                txtMoneyTrue.setText("￥" + (UI.toFloat(editMoney) - UI.toFloat(editMoney) * rate));

            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SelectBankEvent item) {
        bank_id = item.id;
        Glide.with(this).load(item.icon).into(imgBankIcon);
        Spanned txt_bank_content = Spans.with(this).font(item.name, x30, 0xff333333).style(Typeface.BOLD).
                font("\n" + item.bankcard, x30, 0xff999999).
                build();
        txtBankInfo.setText(txt_bank_content);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (is_request) {
            getBankCard();
            getCommissionCheckApply();
        }
    }

    public void getBankCard() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getBankCardList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.datas != null && result.datas.size() != 0) {
                        is_has_bankcard = true;
                        viewHasBankcard.setVisibility(View.VISIBLE);
                        layoutHasBankcard.setVisibility(View.VISIBLE);
                        BankCardListModel.DatasBean item = result.datas.get(0);
                        Glide.with(this).load(item.icon).into(imgBankIcon);
                        Spanned txt_bank_content = Spans.with(this).font(item.name, x30, 0xff333333).style(Typeface.BOLD).
                                font("\n" + item.bankcard, x30, 0xff999999).
                                build();
                        txtBankInfo.setText(txt_bank_content);
                        bank_id = item.id;
                    } else {
                        viewHasBankcard.setVisibility(View.GONE);
                        layoutHasBankcard.setVisibility(View.GONE);
                        is_has_bankcard = false;
                    }
                });
    }

    public void getCommissionCheckApply() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getCommissionCheckApply().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    rate = Float.valueOf(result.datas.rate) / 100;
                    txtRate.setText(result.datas.rate + "%");
                });
    }

    public void getCommissionApply(String bankcard_id, String money) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        CommissoinCheckApplyBean bean = new CommissoinCheckApplyBean();
        bean.bankcard_id = bankcard_id;
        bean.money = money;
        Api.api_service.getCommissionApply(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    showFinishTipsDialog();
                });
    }

    private void showTipsDialog() {
        Dialog.showDefaultDialog(this, "", "第三方平台收取的交易手续费率", "", "我知道了", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {

            }
        });
    }

    private void showFinishTipsDialog() {
        Dialog.showDefaultDialog(this, "", "您的提现申请已经提交，平台审核通过后，将直接提现到你选择的相关账户。", "", "我知道了", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {

            }

            @Override
            public void cancel() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_change_bankcard, R.id.btn_submit, R.id.btn_rate})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_rate:
                showTipsDialog();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_change_bankcard:
                if (is_has_bankcard) {
                    is_request = false;
                    Util.startActivity(this, BankListActivity.class);
                } else {
                    is_request = true;
                    Util.startActivity(this, BankCardSelectEmptyActivity.class);
                }

                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(bank_id)) {
                    ToastUtil.makeText(this, "银行卡不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editMoney))) {
                    ToastUtil.makeText(this, "提现金额不能为空");
                    return;
                }
                getCommissionApply(bank_id, UI.toString(editMoney));
                break;
        }
    }
}
